"""
主路由模块
处理首页、关于、帮助等页面
"""
from flask import Blueprint, render_template, jsonify, current_app
from flask_login import login_required, current_user

from app.auth.decorators import handle_exceptions
from app.utils.helpers import format_timestamp

main_bp = Blueprint('main', __name__)

@main_bp.route('/')
def index():
    """
    首页
    显示平台概览和最新动态
    """
    try:
        from app.models.forum import Post, Category
        from app.models.user import User
        from app import db
        
        # 获取最新帖子
        recent_posts = Post.query.filter_by(is_published=True)\
            .order_by(Post.created_at.desc())\
            .limit(5)\
            .all()
        
        # 获取热门分类
        popular_categories = Category.query.filter_by(is_active=True)\
            .order_by(Category.post_count.desc())\
            .limit(6)\
            .all()
        
        # 获取用户统计
        user_count = User.query.filter_by(is_active=True).count()
        post_count = Post.query.filter_by(is_published=True).count()
        
        # 获取在线用户（简化版）
        online_users = User.query.filter_by(is_online=True)\
            .order_by(User.last_seen.desc())\
            .limit(10)\
            .all()
        
        return render_template('main/index.html',
                            recent_posts=recent_posts,
                            popular_categories=popular_categories,
                            user_count=user_count,
                            post_count=post_count,
                            online_users=online_users)
    
    except Exception as e:
        current_app.logger.error(f"首页加载失败: {str(e)}")
        # 出错时返回基础页面
        return render_template('main/index.html',
                            recent_posts=[],
                            popular_categories=[],
                            user_count=0,
                            post_count=0,
                            online_users=[])

@main_bp.route('/about')
def about():
    """
    关于页面
    介绍平台信息和团队
    """
    return render_template('main/about.html')

@main_bp.route('/help')
def help():
    """
    帮助页面
    提供使用指南和常见问题
    """
    return render_template('main/help.html')

@main_bp.route('/contact')
def contact():
    """
    联系我们页面
    """
    return render_template('main/contact.html')

@main_bp.route('/privacy')
def privacy():
    """
    隐私政策页面
    """
    return render_template('main/privacy.html')

@main_bp.route('/terms')
def terms():
    """
    服务条款页面
    """
    return render_template('main/terms.html')

@main_bp.route('/status')
@handle_exceptions
def status():
    """
    系统状态页面
    显示平台运行状态和统计信息
    """
    from app.models.user import User
    from app.models.forum import Post, Comment, Category
    from app.models.chat import ChatRoom, Message
    from app import db
    import psutil
    import os
    
    # 基本统计
    stats = {
        'users': {
            'total': User.query.count(),
            'active': User.query.filter_by(is_active=True).count(),
            'online': User.query.filter_by(is_online=True).count(),
            'admins': User.query.filter_by(role='admin').count()
        },
        'forum': {
            'posts': Post.query.filter_by(is_published=True).count(),
            'comments': Comment.query.count(),
            'categories': Category.query.filter_by(is_active=True).count()
        },
        'chat': {
            'rooms': ChatRoom.query.filter_by(is_active=True).count(),
            'messages': Message.query.count()
        }
    }
    
    # 系统信息
    system_info = {
        'platform': {
            'name': 'SteHub',
            'version': '2.0.0',
            'mode': current_app.config.get('RUN_MODE', 'local')
        },
        'database': {
            'url': current_app.config.get('SQLALCHEMY_DATABASE_URI', '')[:50] + '...' if current_app.config.get('SQLALCHEMY_DATABASE_URI') else 'Unknown',
            'tables': len(db.metadata.tables)
        },
        'storage': {
            'mode': current_app.config.get('RUN_MODE', 'local'),
            'upload_folder': current_app.config.get('UPLOAD_FOLDER', '')
        }
    }
    
    # 系统资源使用情况
    try:
        process = psutil.Process(os.getpid())
        memory_usage = process.memory_info().rss / 1024 / 1024  # MB
        
        system_info['resources'] = {
            'memory_usage_mb': round(memory_usage, 2),
            'cpu_percent': psutil.cpu_percent(interval=1),
            'disk_usage': psutil.disk_usage('/').percent
        }
    except Exception as e:
        current_app.logger.warning(f"无法获取系统资源信息: {str(e)}")
        system_info['resources'] = {
            'memory_usage_mb': 0,
            'cpu_percent': 0,
            'disk_usage': 0,
            'error': str(e)
        }
    
    return render_template('main/status.html',
                         stats=stats,
                         system_info=system_info)

@main_bp.route('/search')
@handle_exceptions
def search():
    """
    搜索页面
    支持帖子、用户等内容搜索
    """
    from flask import request
    
    query = request.args.get('q', '').strip()
    search_type = request.args.get('type', 'all')
    page = request.args.get('page', 1, type=int)
    
    results = []
    total_results = 0
    
    if query:
        from app.models.forum import Post
        from app.models.user import User
        from sqlalchemy import or_
        
        if search_type in ['all', 'posts']:
            # 搜索帖子
            post_query = Post.query.filter(
                or_(
                    Post.title.ilike(f'%{query}%'),
                    Post.content.ilike(f'%{query}%')
                ),
                Post.is_published == True
            )
            
            if search_type == 'posts':
                posts = post_query.paginate(
                    page=page, per_page=10, error_out=False
                )
                results.extend(posts.items)
                total_results += posts.total
            else:
                # 在全部搜索中只显示前3个帖子
                posts = post_query.limit(3).all()
                results.extend(posts)
        
        if search_type in ['all', 'users']:
            # 搜索用户
            user_query = User.query.filter(
                or_(
                    User.username.ilike(f'%{query}%'),
                    User.email.ilike(f'%{query}%')
                ),
                User.is_active == True
            )
            
            if search_type == 'users':
                users = user_query.paginate(
                    page=page, per_page=10, error_out=False
                )
                results.extend(users.items)
                total_results += users.total
            else:
                # 在全部搜索中只显示前3个用户
                users = user_query.limit(3).all()
                results.extend(users)
    
    return render_template('main/search.html',
                         query=query,
                         search_type=search_type,
                         results=results,
                         total_results=total_results,
                         page=page)

@main_bp.route('/health')
def health_check():
    """
    健康检查端点
    用于负载均衡和监控系统
    """
    try:
        from app import db
        # 测试数据库连接
        db.session.execute('SELECT 1')
        
        # 检查关键服务状态
        status = {
            'status': 'healthy',
            'database': 'connected',
            'timestamp': format_timestamp(),
            'version': '2.0.0'
        }
        
        return jsonify(status), 200
    
    except Exception as e:
        current_app.logger.error(f"健康检查失败: {str(e)}")
        return jsonify({
            'status': 'unhealthy',
            'error': str(e),
            'timestamp': format_timestamp()
        }), 503

@main_bp.route('/metrics')
@login_required
def metrics():
    """
    系统指标端点
    返回平台运行指标（需要登录）
    """
    from app.models.user import User
    from app.models.forum import Post, Comment
    from app.models.chat import Message
    from datetime import datetime, timedelta
    
    # 今日统计
    today = datetime.utcnow().date()
    today_start = datetime(today.year, today.month, today.day)
    
    metrics_data = {
        'users': {
            'total': User.query.count(),
            'new_today': User.query.filter(User.created_at >= today_start).count(),
            'online': User.query.filter_by(is_online=True).count()
        },
        'content': {
            'posts_total': Post.query.filter_by(is_published=True).count(),
            'posts_today': Post.query.filter(
                Post.created_at >= today_start,
                Post.is_published == True
            ).count(),
            'comments_total': Comment.query.count(),
            'comments_today': Comment.query.filter(
                Comment.created_at >= today_start
            ).count()
        },
        'chat': {
            'messages_total': Message.query.count(),
            'messages_today': Message.query.filter(
                Message.created_at >= today_start
            ).count()
        }
    }
    
    return jsonify(metrics_data)

@main_bp.route('/dashboard')
@login_required
def dashboard():
    """
    用户仪表板
    显示用户的个人数据和活动
    """
    from app.models.forum import Post, Comment
    from app.models.chat import Message
    
    # 获取用户的最新活动
    user_posts = Post.query.filter_by(author_id=current_user.id)\
        .order_by(Post.created_at.desc())\
        .limit(5)\
        .all()
    
    user_comments = Comment.query.filter_by(author_id=current_user.id)\
        .order_by(Comment.created_at.desc())\
        .limit(5)\
        .all()
    
    # 获取用户统计数据
    user_stats = {
        'posts_count': Post.query.filter_by(author_id=current_user.id).count(),
        'comments_count': Comment.query.filter_by(author_id=current_user.id).count(),
        'likes_received': sum(post.like_count for post in user_posts)
    }
    
    return render_template('main/dashboard.html',
                         user_posts=user_posts,
                         user_comments=user_comments,
                         user_stats=user_stats)

@main_bp.app_errorhandler(404)
def page_not_found(error):
    """
    404错误处理
    """
    return render_template('errors/404.html'), 404

@main_bp.app_errorhandler(500)
def internal_server_error(error):
    """
    500错误处理
    """
    current_app.logger.error(f"服务器内部错误: {str(error)}")
    return render_template('errors/500.html'), 500

@main_bp.app_context_processor
def inject_global_variables():
    """
    注入全局变量到所有模板
    """
    return {
        'app_name': 'SteHub',
        'app_version': '2.0.0',
        'current_year': datetime.utcnow().year
    }